package org.jaaksi.customviewdemo.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Path
import android.util.AttributeSet
import android.view.View
import org.jaaksi.customviewdemo.R

/**
 * 属性：箭头方向
 * 不考虑Padding
 */
class TriangleView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    companion object {
        const val LEFT: Int = 1
        const val TOP: Int = 2
        const val RIGHT: Int = 3
        const val BOTTOM: Int = 4
    }

    // 箭头朝向
    var orientation = TOP

    private val path = Path()

    init {
        if (attrs != null) {
            val attr = context.obtainStyledAttributes(attrs, R.styleable.TriangleView)
            orientation = attr.getInt(R.styleable.TriangleView_tv_orientation, orientation)
            attr.recycle()
        }

    }

    override fun draw(canvas: Canvas) {
        val id = canvas.save()
        path.reset()
        when (orientation) {
            LEFT -> {
                path.moveTo(0f, height / 2f)
                path.lineTo(width.toFloat(), 0f)
                path.lineTo(width.toFloat(), height.toFloat())
            }
            TOP -> {
                path.moveTo(width / 2f, 0f)
                path.lineTo(width.toFloat(), height.toFloat())
                path.lineTo(0f, height.toFloat())
            }
            RIGHT -> {
                path.moveTo(width.toFloat(), height / 2f)
                path.lineTo(0f, 0f)
                path.lineTo(0f, height.toFloat())
            }
            BOTTOM -> {
                path.moveTo(width / 2f, height.toFloat())
                path.lineTo(0f, 0f)
                path.lineTo(width.toFloat(), 0f)
            }
        }
        path.close()
        canvas.clipPath(path)
        super.draw(canvas)
        canvas.restoreToCount(id)
    }

}